package com.ruoyi.project.mgr.adjust.controller;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.mgr.adjust.domain.MgrAdjustApply;
import com.ruoyi.project.mgr.adjust.service.IMgrAdjustApplyService;
import com.ruoyi.project.mgr.adjust.vo.AdjustListVO;
import com.ruoyi.project.mgr.adjust.vo.NoticeListVO;
import com.ruoyi.project.mgr.arrange.domain.MgrCourseArrange;
import com.ruoyi.project.mgr.arrange.service.IMgrCourseArrangeService;
import com.ruoyi.project.mgr.course.service.IMgrCourseService;
import com.ruoyi.project.mgr.room.domain.MgrRoom;
import com.ruoyi.project.mgr.room.service.IMgrRoomService;
import com.ruoyi.project.system.dict.service.IDictDataService;
import com.ruoyi.project.system.role.domain.Role;
import com.ruoyi.project.system.role.service.IRoleService;
import com.ruoyi.project.system.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 调课申请Controller
 *
 * @author .
 * @date 2020-02-15
 */
@Controller
@RequestMapping("/mgr/adjust")
public class MgrAdjustApplyController extends BaseController
{
    private String prefix = "mgr/adjust";

    @Autowired
    private IMgrAdjustApplyService mgrAdjustApplyService;

    @Autowired
    private IMgrCourseArrangeService mgrCourseArrangeService;

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IMgrCourseArrangeService courseArrangeService;
    @Autowired
    private IMgrRoomService mgrRoomService;
    @Autowired
    private IMgrCourseService mgrCourseService;
    @Autowired
    private IUserService userService;

    @Autowired
    private IDictDataService dictDataService;

    @GetMapping()
    public String apply()
    {
        return prefix + "/adjust";
    }

    /**
     * 查询调课申请列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(MgrAdjustApply mgrAdjustApply)
    {
        startPage();
        List<MgrAdjustApply> list = mgrAdjustApplyService.selectMgrAdjustApplyList(mgrAdjustApply);
        return getDataTable(list);
    }



    /**
     * 新增保存调课申请
     */
    @Log(title = "换课申请", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(MgrAdjustApply mgrAdjustApply)
    {
        MgrAdjustApply adjustApply = new MgrAdjustApply();
        adjustApply.setArrangeId(mgrAdjustApply.getArrangeId());
        adjustApply.setOperateStatus(0);
        List<MgrAdjustApply> adjustApplyList = mgrAdjustApplyService.selectMgrAdjustApplyList(adjustApply);
        if (adjustApplyList != null && adjustApplyList.size() > 0) {
            return error("当前课程有未处理的申请！");
        }
        MgrCourseArrange arrange = mgrCourseArrangeService.selectMgrCourseArrangeById(mgrAdjustApply.getAfterArrangeId());
        mgrAdjustApply.setNowTeacherId(arrange.getTeacherId());
        mgrAdjustApply.setAfterArrangeId(mgrAdjustApply.getAfterArrangeId());
        mgrAdjustApply.setNowTeacherName(userService.selectUserById(arrange.getTeacherId()).getUserName());
        mgrAdjustApply.setNowRommCode(mgrRoomService.selectMgrRoomById(arrange.getRoomId()).getRoomCode());
        mgrAdjustApply.setNowCourseDate(arrange.getCourseDate());
        mgrAdjustApply.setNowCourseName(mgrCourseService.selectMgrCourseById(arrange.getCourseId()).getCourseName());
        mgrAdjustApply.setNowTimeSlot(arrange.getTimeSlot());
        mgrAdjustApply.setType("0");
        return toAjax(mgrAdjustApplyService.insertMgrAdjustApply(mgrAdjustApply));
    }

    /**
     * 调课
     * @return
     */
    @ResponseBody
    @PostMapping("/exchangeCourse")
    public AjaxResult exchangeCourse(MgrCourseArrange courseArrange) {
        MgrCourseArrange mgrCourseArrange = mgrCourseArrangeService.selectMgrCourseArrangeById(courseArrange.getId());
        if (!courseArrange.getRoomId().equals(mgrCourseArrange.getRoomId()) ||
                courseArrange.getCourseDate().compareTo(mgrCourseArrange.getCourseDate()) != 0 ||
                !courseArrange.getTimeSlot().equals(mgrCourseArrange.getTimeSlot())) {

            MgrAdjustApply adjustApply = new MgrAdjustApply();
            adjustApply.setArrangeId(courseArrange.getId());
            adjustApply.setOperateStatus(0);
            List<MgrAdjustApply> adjustApplyList = mgrAdjustApplyService.selectMgrAdjustApplyList(adjustApply);
            if (adjustApplyList != null && adjustApplyList.size() > 0) {
                return error("当前课程有未处理的申请！");
            }
            adjustApply.setType("1");
            adjustApply.setNowTeacherId(mgrCourseArrange.getTeacherId());
            adjustApply.setNowTeacherName(userService.selectUserById(mgrCourseArrange.getTeacherId()).getUserName());
            adjustApply.setNowRommCode(mgrRoomService.selectMgrRoomById(courseArrange.getRoomId()).getRoomCode());
            adjustApply.setNowCourseDate(courseArrange.getCourseDate());
            adjustApply.setNowCourseName(mgrCourseService.selectMgrCourseById(mgrCourseArrange.getCourseId()).getCourseName());
            adjustApply.setNowTimeSlot(courseArrange.getTimeSlot());
            mgrAdjustApplyService.insertMgrAdjustApply(adjustApply);
        }
        return success();
    }


    @GetMapping("myArrange")
    public String myArrange(ModelMap modelMap)
    {
        if (!ShiroUtils.getSysUser().isAdmin()) {
            List<Role> roleList = roleService.selectRolesByUserId(ShiroUtils.getUserId()).stream().filter(s-> s.isFlag()).collect(Collectors.toList());
            Role role = roleList.get(0);
            if ("teacher".equals(role.getRoleKey())) {
                modelMap.put("teacherId", ShiroUtils.getUserId());
            }
        }
        return prefix + "/my_arrange";
    }

    /**
     * 查询教师课程安排列表
     */
    @PostMapping("/teacherList")
    @ResponseBody
    public TableDataInfo teacherList(MgrCourseArrange mgrCourseArrange)
    {
        startPage();

        List<MgrCourseArrange> list = mgrCourseArrangeService.selectMyCourseArrangeList(mgrCourseArrange);
        list.stream().forEach(s -> {
            if (s.getApplyId() == null) {
                s.setExplain("无");
            } else {
                s.setExplain("有");
            }
        });
        return getDataTable(list);
    }


    @GetMapping("/selectCourse/{id}")
    public String selectCourse(@PathVariable("id")Long id, ModelMap modelMap)
    {
        modelMap.put("arrangeId", id);
        modelMap.put("teacherId", ShiroUtils.getUserId());
        return prefix + "/selectCourse";
    }

    /**
     * 查询其他教师课程安排列表
     */
    @PostMapping("/courseList")
    @ResponseBody
    public TableDataInfo courseList(MgrCourseArrange mgrCourseArrange)
    {
        startPage();
        List<MgrCourseArrange> list = mgrCourseArrangeService.selectOtherCourseArrangeList(mgrCourseArrange);
        return getDataTable(list);
    }


    @ResponseBody
    @GetMapping("/agree/{id}")
    public AjaxResult agree(@PathVariable("id") Long id) {
        MgrAdjustApply adjustApply = mgrAdjustApplyService.selectMgrAdjustApplyById(id);
        if ("1".equals(adjustApply.getType())) {
            MgrCourseArrange mgrCourseArrange = new MgrCourseArrange();
            mgrCourseArrange.setDay(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, adjustApply.getCourseDate()));
            mgrCourseArrange.setTimeSlot(adjustApply.getNowTimeSlot());
            MgrRoom mgrRoom = new MgrRoom();
            mgrRoom.setRoomCode(adjustApply.getNowRommCode());
            mgrCourseArrange.setRoomId(mgrRoomService.selectMgrRoomList(mgrRoom).get(0).getRoomId());
            List<MgrCourseArrange> courseArrangeList = mgrCourseArrangeService.selectMgrCourseArrangeList(mgrCourseArrange);
            if (courseArrangeList != null && courseArrangeList.size() > 0) {
                return error("当前申请调整时间的教室已被占用！");
            }
        }

        return toAjax(mgrAdjustApplyService.agree(adjustApply));
    }

    /**
     * 打开填写拒绝理由页面
     * @param id
     * @param modelMap
     * @return
     */
    @GetMapping("/openRefuse/{id}")
    public String openRefuse(@PathVariable("id") Long id, ModelMap modelMap) {
        modelMap.put("id", id);
        return prefix + "/refuse";
    }

    @ResponseBody
    @PostMapping("/refuse")
    public AjaxResult refuse(MgrAdjustApply mgrAdjustApply) {
        return toAjax(mgrAdjustApplyService.refuse(mgrAdjustApply));
    }


    @GetMapping("/notice")
    public String notice(ModelMap modelMap) {
        List<NoticeListVO> noticeList = new ArrayList<>();
        if (!ShiroUtils.getSysUser().isAdmin()) {

            List<Role> roleList = roleService.selectRolesByUserId(ShiroUtils.getUserId()).stream().filter(s-> s.isFlag()).collect(Collectors.toList());
            Role role = roleList.get(0);
            if ("student".equals(role.getRoleKey())) {
                noticeList = mgrAdjustApplyService.selectStudentNotice(ShiroUtils.getSysUser().getClazzId());
            } else if ("teacher".equals(role.getRoleKey())) {
                noticeList = mgrAdjustApplyService.selectTeacherNotice(ShiroUtils.getUserId());
                noticeList.stream().forEach(s-> s.setTeacher(true));
            }
        }
        modelMap.put("notices", noticeList);
        return prefix + "/notice";
    }

    @GetMapping("/exchange/{id}")
    public String exchange(@PathVariable("id") Long id, ModelMap modelMap) {
        MgrCourseArrange courseArrange = courseArrangeService.selectMgrCourseArrangeById(id);
        MgrRoom mgrRoom = new MgrRoom();
        mgrRoom.setStatus(0);
        List<MgrRoom> roomList = mgrRoomService.selectMgrRoomList(mgrRoom);
        roomList.stream().forEach(s -> {
            if (s.getRoomId().equals(courseArrange.getRoomId())) {
                s.setFlag(true);
            }
        });
        modelMap.put("courseName", mgrCourseService.selectMgrCourseById(courseArrange.getCourseId()).getCourseName());
        modelMap.put("teacher", userService.selectUserById(courseArrange.getTeacherId()).getUserName());
        modelMap.put("rooms", roomList);
        modelMap.put("mgrCourseArrange", courseArrange);
        return prefix + "/exchange";
    }
}